有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

java如何使此方法可重用?

我有两个类使用类似的方法:

method classA() {
    some variable initialization
    get this common interface In

    try {
        do something
        In.methodAA();

    catch () {
        do something
    }
}


method classB() {
    some variable initialization
    get this common interface In

    try {
        do something
        In.methodBB()

    catch () {
        do something 
    }
}

如果可能的话,我想在父类中放一个方法,因为主要的区别是在接口上调用的方法。如何实现这一点

我用的是java7

谢谢!


共 (2) 个答案

  1. # 1 楼答案

    我将使用由a和B类实现的公共接口

    interface Behaviour {
        void execute();
    }
    
    public class A implements Behaviour {
        @Override
        public void execute() {
            // do method A logic
        }
    }
    
    public class B implements Behaviour {
        @Override
        public void execute() {
            // do method B logic
        }
    
    }
    
    public class TemplateClass {
        private Behaviour behaviour;
    
        public TemplateClass(Behaviour behaviour) {
            this.behaviour = behaviour;
        }
    
        public void commonMethod() {
            try {
                // do something
                // ..
    
                // call specific logic
                behaviour.execute();
            } catch (Exception e) {
                // handle ex
            }
    
        }
    }
    

    用法

    //using A class
    TemplateClass polymorphicVariable = new TemplateClass(new A());
    polymorphicVariable.commonMethod();
    
    //using B class
    polymorphicVariable = new TemplateClass(new B());
    polymorphicVariable.commonMethod();
    
  2. # 2 楼答案

    我会使用第三个实用程序类

    static method classC(classType){
    
        some variable initialization
        get this common interface In
        try {
          do something
    
          if (classType is A)
            In.methodAA()
          else 
            In.methodBB()
    
        } catch () {
          do something
        }
    }